<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if(ENTRANCE=='index'){
   think\Url::root(URL_PATH.'index.php');
}
/**
 * 删除文件夹
 * @param string $dirname
 * @return boolean
 */
function rmdirs($dirname)
{
    if (!is_dir($dirname))
        return false;
    $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($files as $fileinfo)
    {
        $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
        $todo($fileinfo->getRealPath());
    }
    @rmdir($dirname);
    return true;
}

/**
 * 复制文件夹
 * @param string $source 源文件夹
 * @param string $dest 目标文件夹
 */
function copydirs($source, $dest){
    if (!is_dir($dest))
    {
        mkdir($dest, 0755);
    }
    foreach (
    $iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
    )
    {
        if ($item->isDir())
        {
            $sontDir = $dest . DS . $iterator->getSubPathName();
            if (!is_dir($sontDir))
            {
                mkdir($sontDir);
            }
        }
        else
        {
            copy($item, $dest . DS . $iterator->getSubPathName());
        }
    }
}

function deldir($path,$delDir=true) {
	if (is_dir($path) == false){
		return FALSE;
	}
    $handle = opendir($path);
    if ($handle){
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? deldir("$path/$item", $delDir) : @unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return @rmdir($path);
    }else {
        if (file_exists($path)) {
            return @unlink($path);
        } else {
            return FALSE;
        }
    }
}
//将数组保存为文件
function F($name,$value='',$path='data'){
	$path=RUNTIME_PATH.$path.'/';
	$file = new \com\File();
    static $_cache  =   array();
    $filename       =   $path . $name . '.php';
    if ('' !== $value) {
        if (is_null($value)) {
            // 删除缓存
            if(false !== strpos($name,'*')){
                return false; // TODO 
            }else{
                unset($_cache[$name]);
                return $file->unlink($filename,'F');
            }
        } else {
            $file->put($filename,serialize($value),'F');
            // 缓存数据
            $_cache[$name]  =   $value;
            return ;
        }
    }
    // 获取缓存数据
    if (isset($_cache[$name]))
        return $_cache[$name];
    if ($file->has($filename,'F')){
        $value      =   unserialize($file->read($filename,'F'));
        $_cache[$name]  =   $value;
    } else {
        $value          =   false;
    }
    return $value;
}
// 应用公共文件
function rand_string($len = 6, $type = '', $addChars = '') {
	$str = '';
	switch ($type) {
	case 0:
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
		break;
	case 1:
		$chars = str_repeat('0123456789', 3);
		break;
	case 2:
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
		break;
	case 3:
		$chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
		break;
	case 4:
		$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借" . $addChars;
		break;
	default:
		// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
		$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
		break;
	}
	if ($len > 10) {
		//位数过长重复字符串一定次数
		$chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
	}
	if ($type != 4) {
		$chars = str_shuffle($chars);
		$str   = substr($chars, 0, $len);
	} else {
		// 中文随机字
		for ($i = 0; $i < $len; $i++) {
			$str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
		}
	}
	return $str;
}
// 去掉换行
function nr($str){
	$str = str_replace(array("<nr/>","<rr/>"),array("\n","\r"),$str);
	return trim($str);
}
//去掉连续空白
function nb($str){
	$find    = ['~>\s+<~', '~>(\s+\n|\r)~'];
    $replace = ['><', '>'];
    $str = preg_replace($find, $replace, $str);
	return trim($str);
}
 //字符串截取(同时去掉HTML与空白)
function msubstr($str, $start=0, $length, $suffix=false){
	return zanpian_msubstr(preg_replace('/<[^>]+>/','',preg_replace("/[\r\n\t ]{1,}/",' ',nb($str))),$start,$length,'utf-8',$suffix);
}
function zanpian_msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$length_new = $length;
	$length_chi='';
	for($i=$start; $i<$length; $i++){
		if(ord($match[0][$i])> 0xa0){
			//中文
		}else{
			$length_new++;
			$length_chi++;
		}
	}
	if($length_chi<$length){
		$length_new = intval($length)+(intval($length_chi)/2);
	}
	$slice = join("",array_slice($match[0], $start, $length_new));
    if($suffix && $slice != $str){
		return $slice."…";
	}
    return $slice;
}
// 格式化采集影片主演
function format_text($vodactor){
	return str_replace(',,',',',str_replace(array('/','，','|','、',' ','，',',,'),',',$vodactor));	
}
function zanpian_get_tag($title,$content){
    $url ='http://zhannei.baidu.com/api/customsearch/keywords?title='.rawurlencode($title).rawurlencode(msubstr(strip_tags($content),0,200));
    $data = zanpian_curl_get($url);
    if($data) {
        $json = @json_decode($data,true);
        if($json){
            if(!empty($json['result']['res']['keyword_list']) && is_array($json['result']['res']['keyword_list'])){
                $res = $json['result']['res']['keyword_list'];
                return join(',',$res);
            }
        }
        else{

        }
    }
    return false;
}
function zanpian_curl_get($url,$time=30,$heads=array(),$cookie='',$post=''){
	if(function_exists('curl_init')){
        $ch = @curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_TIMEOUT,$time);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        if(!empty($cookie)){
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        if(count($heads)>0){
            curl_setopt ($ch, CURLOPT_HTTPHEADER , $heads );
        }
		//post
		if($post){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}		
        $response = @curl_exec($ch);
		$http = parse_url($url);
		if($http['scheme'] == 'https'){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		}	
        if(curl_errno($ch)){//出错则显示错误信息
        //print curl_error($ch);die;
        }
		$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		if($httpCode=='502' || $httpCode=='404' || $httpCode!='200'){
			return false;
		}
        curl_close($ch); //关闭curl链接
        return $response;//显示返回信息
	}else{
	    $ctx = stream_context_create(array('http'=>array('timeout'=>$time)));
	    $content = @file_get_contents($url, 0, $ctx);
		if(strpos($http_response_header[0],'502') >0 || strpos($http_response_header[0],'404') >0){
			return false;
		}
	    if($content){
		    return $content;
	    }
	    return false;
	}
}

function zanpian_curl_post($url,$data,$heads=array(),$cookie=''){
    $ch = @curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLINFO_CONTENT_LENGTH_UPLOAD,$data);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    if(!empty($cookie)){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if(count($heads)>0){
        curl_setopt ($ch, CURLOPT_HTTPHEADER , $heads );
    }
    $response = @curl_exec($ch);
    if(curl_errno($ch)){//出错则显示错误信息
        //print curl_error($ch);
    }
    curl_close($ch); //关闭curl链接
    return $response;//显示返回信息
}	


function zanpiancms_param_url(){
	$param = [];
	$param['id'] = input('id/d','');
	$param['cid'] = input('cid/d','');
	$param['dir'] = htmlspecialchars(input('dir/s',''));
	$param['vid'] = input('vid/d','');
	$param['vcid'] = input('vcid/d','');
	$param['vdir'] = htmlspecialchars(input('vdir/s',''));	
	$param['sid'] = input('sid/d','');
	$param['pid'] = input('pid/d','');
	$param['op'] = input('op/d','');
	$param['uid'] = input('uid/d','');
	$param['pinyin'] = htmlspecialchars(input('pinyin/s',''));
	$param['letter'] = htmlspecialchars(input('letter/s',''));
	$param['tag'] = htmlspecialchars(urldecode(trim(input('tag/s',''))));
	$param['wd'] = htmlspecialchars(urldecode(trim(input('wd/s',''))));
	$param['play'] = htmlspecialchars(urldecode(trim(input('play/s',''))));
	$param['year'] = input('year/d','');
	$param['month'] = input('month/d','');
	$param['lang'] = htmlspecialchars(urldecode(trim(input('lang/s',''))));
	$param['area'] = htmlspecialchars(urldecode(trim(input('area/s',''))));
	$param['earea'] = htmlspecialchars(urldecode(trim(input('earea/s',''))));
	$param['actor'] = htmlspecialchars(urldecode(trim(input('actor/s',''))));
	$param['director'] = htmlspecialchars(urldecode(trim(input('director/s',''))));
	$param['stars'] = input('stars/d','');
	$param['zy'] = htmlspecialchars(urldecode(trim(input('zy/s',''))));
	$param['sex'] = htmlspecialchars(urldecode(trim(input('sex/s',''))));
	$param['type'] = htmlspecialchars(urldecode(trim(input('type/s',''))));
	$param['filmtime'] = htmlspecialchars(input('filmtime/s',''));
	$param['mcid'] = input('mcid/d','');
	$param['mename'] = htmlspecialchars(input('mename/s',''));
	$param['lz'] = input('lz/d','');
	$param['picm'] = input('picm/d','');
	$param['cm'] = input('cm/d','');
	$param['gold'] = input('gold/d','');
	$param['limit'] = input('limit/d','');
	$param['order'] = input('order/s','');
	$param['p'] = input('p/d',1);
	// by plain
	$param['ids'] = htmlspecialchars(urldecode(trim(input('ids/s',''))));
	$param['not'] = htmlspecialchars(urldecode(trim(input('not/s',''))));
	$param['name'] = htmlspecialchars(urldecode(trim(input('name/s',''))));
	return $param;
}
//返回安全的orderby
function order_by($order = 'addtime'){
	if(empty($order)){
		return '';
	}
	$array = array();
	$array['addtime'] = 'addtime';
	$array['id'] = 'id';
	$array['hits'] = 'hits';
	$array['hits_month'] = 'hits_month';
	$array['hits_week'] = 'hits_week';
	$array['stars'] = 'stars';
	$array['up'] = 'up';
	$array['down'] = 'down';
	$array['gold'] = 'gold';
	$array['golder'] = 'golder';
	$array['year'] = 'year';
	$array['letter'] = 'letter';
	$array['filmtime'] = 'filmtime';
	$array['oid'] = 'oid';
	return $array[trim($order)];
}
function order_check($order = ''){
	if(empty($order)){
		return '';
	}
	$array = array();
	$array['addtime'] = 'addtime';
	$array['uptime'] = 'uptime';
	$array['name'] = 'name';
	$array['id'] = 'id';
	$array['hits'] = 'hits';
	$array['hits_day'] = 'hits_day';
	$array['hits_week'] = 'hits_week';
	$array['hits_month'] = 'hits_month';
	$array['hits_week'] = 'hits_week';
	$array['hits_lasttime'] = 'hits_lasttime';
	$array['stars'] = 'stars';
	$array['up'] = 'up';
	$array['down'] = 'down';
	$array['gold'] = 'gold';
	$array['golder'] = 'golder';
	$array['year'] = 'year';
	$array['letter'] = 'letter';
	$array['filmtime'] = 'filmtime';
	$array['oid'] = 'oid';
	$array['status'] = 'status';
	$orderarray = explode(' ',$order);
    if(!in_array($orderarray[1],['asc','desc'])){
        $by='desc';
    }else{
		$by=$orderarray[1];
	}
    $orders=explode('_',$orderarray[0]);
	unset($orders[0]);
	$orders= implode('_',$orders);
	if($array[trim($orders)]){
	   return $order;	
	}
}


function list_search($list,$condition) {
    if(is_string($condition))
        parse_str($condition,$condition);
    // 返回的结果集合
    $resultSet = array();
    foreach ($list as $key=>$data){
        $find   =   true;// fixed
        foreach ($condition as $field=>$value){
            if(isset($data[$field])) {
                if(0 === strpos($value,'/')) {
                    $find   =  $find && preg_match($value,$data[$field]);// fixed
                }else{
                    $find = $find && $data[$field]==$value;// fixed
                }
            }else{
                $find=false;// fixed
            }
        }
        if($find)
            $resultSet[]     =   &$list[$key];
    }
    return $resultSet;
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
	//数据类型检测
	if (!is_array($data)) {
		$data = (array) $data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名
	return $sign;
}

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_login() {
	$user = session('user_auth');
	if(empty($user)) {
		return 0;
	}else{
		return session('user_auth_sign') == data_auth_sign($user) ? $user['user_id'] : 0;
	}
}
/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function member_login() {
	$user = session('member_auth');
	if (empty($user)) {
		return 0;
	} else {
		return session('member_auth_sign') == data_auth_sign($user) ? $user['member_id'] : 0;
	}
}
/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_administrator($uid = null){
	$uid = is_null($uid) ? member_login() : $uid;
	return $uid && (intval($uid) === config('user_administrator'));
}

//写入文件
function zanpian_write_file($l1, $l2=''){
	$dir = dirname($l1);
	if(!is_dir($dir)){
		zanpian_mkdirss($dir);
	}
	return @file_put_contents($l1, $l2);
}
//递归创建文件
function zanpian_mkdirss($dirs,$mode=0777) {
	if(!is_dir($dirs)){
		zanpian_mkdirss(dirname($dirs), $mode);
		return @mkdir($dirs, $mode);
	}
	return true;
}
// 数组保存到文件
function zanpian_arr2file($filename, $arr=''){
	if(is_array($arr)){
		$con = var_export($arr,true);
	} else{
		$con = $arr;
	}
	$con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n
	zanpian_write_file($filename, $con);
}

// 获取广告调用地址
function getadsurl($str,$charset="utf-8"){
	$url=str_replace(array('//','/./'),'/',URL_PATH.$GLOBALS['config']['system']['system_adsfile'].'/'.$str.'.js');
	return '<script type="text/javascript" src="'.$url.'" charset="'.$charset.'"></script>';
}
// 查询当前栏目是否存在下级分类
function getlistson($pid){
	$tree= list_search(F('_data/listtree'),'list_id='.$pid);
	if(!empty($tree[0]['son'])){
		return false;
	}else{
	    return true;
	}
}
//去重后的模板栏目ID参数 $cids = array(1,2,3,...)
function getlistarr_tag($cids){
	$cid = '';
	foreach($cids as $key=>$value){
		if(getlistson($value)){
			$cid .= ','.$value;
		}else{
			$cidin = getlistsqlin($value);
			$cid .= ','.$cidin[1];
		}
	}
	$cidarr = explode(',',$cid);
	unset($cidarr[0]);
	$cidarr = array_unique($cidarr);
	return $cidarr;
}
//生成栏目sql查询语句范围
function getlistsqlin($cid){	
	$tree = list_search(F('_data/listtree'),'list_id='.$cid);
	if (!empty($tree[0]['son'])) {
		foreach($tree[0]['son'] as $val){
			$arr['vod_cid'][] = $val['list_id'];
		}
		$channel = $cid.','.implode(',', $arr['vod_cid']);
		return array('IN',''.$channel.'');	
	}
	return $cid;
}
//生成栏目sql查询语句范围
function getlisttree($cid){	
	$tree = list_search(F('_data/listtree'),'list_id='.$cid);
	if (!empty($tree[0]['son'])) {
		foreach($tree[0]['son'] as $val){
			$arr['vod_cid'][] = $val['list_id'];
		}
		$channel = $cid.','.implode(',', $arr['vod_cid']);
		return $channel;	
	}
	return $cid;
}
// 获取与处理人气值
function gethits($id,$sid,$type='insert',$js=false){
	if($js){
		echo '<script type="text/javascript" src="'.url('home/hits/show',array('id'=>$id,'sid'=>$sid,'type'=>$type)).'" charset="utf-8"></script>';
	}else{
		echo '<span class="detail-hits" data-sid="'.$sid.'" data-id="'.$id.'" data-type="'.$type.'"></span>';
	}
}
// 获取栏目相关统计
function getcount($cid,$sid,$time=''){
    $where=array();
    $mode=$GLOBALS['config']['model'];
    if(!empty($mode[$sid]['name']) && $mode[$sid]['id']!= 11 && $mode[$sid]['id']!= 9 && $mode[$sid]['id']!= 8){
        if($time == 999){
            $where[$mode[$sid]['name'].'_cid']=getlistsqlin($cid);
            $where[$mode[$sid]['name'].'_status']=1;
            $where[$mode[$sid]['name'].'_addtime']=array('gt',getxtime(1));
            $count=db($mode[$sid]['name'])->where($where)->cache($mode[$sid]['name'].'_daycount_'.$cid,3600,'count')->count();
        }elseif($time==1){
            $where[$mode[$sid]['name'].'_cid']=array('gt',0);
            $count=db($mode[$sid]['name'])->where($where)->cache($mode[$sid]['name'].'_countid',3600,'count')->count();
        }else {
            $where[$mode[$sid]['name'].'_cid']=getlistsqlin($cid);
            $count=db($mode[$sid]['name'])->where($where)->cache($mode[$sid]['name'].'_countid_'.$cid,3600,'count')->count();
        }
        return $count+0;
    }
}
//获得某天前的时间戳
function getxtime($day){
	$day = intval($day);
	return mktime(23,59,59,date("m"),date("d")-$day,date("y"));
}

//通过栏目参数获取对应参数
function getlist($str,$seach,$type){
	if(!empty($str)){
    $arr = list_search(F('_data/list'),$seach.'='.$str);
	if(empty($arr)){
		return false;
	}else{
	    return $arr[0][$type];
	}
	}
}

//通过栏目ID获取对应的栏目名称/别名等
function getlistname($cid,$type='list_name'){
	if(!empty($cid)){
        $arr= F('_data/list');
	    if($arr[$cid]){
			if($type=='info'){
			   return $arr[$cid];
			}
			   return $arr[$cid][$type];
	    }else{
	        return $cid;
	    }
	}
}
function getlistid($dir){
	if(!empty($dir)){
        $arr = list_search(F('_data/list'),'list_dir='.$dir);
	    if($arr[0]){
			return $arr[0]['list_id'];
	    }
	}
}
function getlistpid($value){
		if($value){
			$pid=getlistname($value,'list_pid');
		    return $pid == 0 ? $value : $pid;
	    }
}
//更具类型ID或者拼音获取拼音或者ID
function get_mcid($cid,$name,$seach,$type){
	if(!empty($cid)){
	    $pid=getlistname($cid,'list_pid');
	    $cid=!empty($pid) ? $pid : $cid;
		$mcid=model('mcat')->listMcid();
		$data = list_search($mcid,array($seach=>$name,'m_list_id'=>$cid));
		if($data[0][$type]){
		   return $data[0][$type];
		}
	}
	return false;	
}
//更具地区中文或拼音获取拼音或中文
function get_area($name,$seach='name',$type='ename'){
	$data= list_search(F('_data/list_area'),$seach.'='.$name);	
	if(empty($data)){
		return false;
	}else{
	    return $data[0][$type];
	}
}
//更具类型ID循环生成URL
function get_mcat_url($mcids,$cid,$k="",$type='<a href="#url#" target="_blank">#name#</a> '){
	if(empty($mcids)){
		return false;
	}
	if(!is_array($mcids)) {
        $mcids = array_filter(explode(',', $mcids));
    }	
	$html = '';
	$mcid=model('mcat')->listMcid();
	foreach($mcids as $key=>$v){
		if(!empty($k) && $key==$k){break;}
		$url = zanpian_type_url('home/vod/type', array('id'=>$cid,'dir'=>getlistname($cid,'list_dir'),'mcid'=>$v,'mename'=>$mcid[$v]['m_ename'],'area'=>"",'earea'=>"",'year'=>"",'letter'=>"",'order'=>""));
		$arr = $mcid[$v]['m_name'];
		
		$html .= str_replace(array('#url#','#name#'),array($url,$arr),$type);
	}
	return $html;
}
//关键字高亮颜色
function get_hilight_ex($string,$keyword,$arr='span',$color="black"){
	if(!empty($keyword)){
	     return preg_replace('/(?!<[^>]*)'.$keyword.'(?![^<]*>)/i','<'.$arr.' color="'.$color.'">'.$keyword.'</'.$arr.'>',$string);
	}else{
		return $string;
	}	
}
//演员角色替换
function zanpian_content_replace($content,$data,$keywords='',$actor='',$role=''){
	if(empty($content)){
	   return $content;
	}
	if(!empty($keywords)){
		preg_match_all('/《([\s\S]*?)》/',$content,$keys);
		if($keys[1]){
			$name_array=array_unique($keys[1]);
			$vod_array=db('vod')->where('vod_name|vod_aliases','in',$name_array)->field('vod_id,vod_name,vod_cid,vod_letters,vod_jumpurl')->select();
            if($vod_array){
		        foreach($vod_array as $key=>$value){
			        $find[$key]='/(?!<[^>]*)'.str_replace('/','\/',$value['vod_name']).'(?![^<]*>)/i';
			        $replace[$key]='<a target="_blank" href="'.zanpian_read_url('home/vod/read',$value).'" title="'.$value['vod_name'].'">'.$value['vod_name'].'</a>';
		        }
		        $content = preg_replace($find,$replace,$content,1);			
			}	
		}
	}
    if(empty($data)){
		return $content;
	}	
	if(!empty($data['vod_actor']) && empty($actor)){
		$array_actor = array_filter(explode(',',$data['vod_actor']));
		foreach($array_actor as $key=>$value){
			if(strpos($content,$value) !== false){
			    $find[$key]='/(?!<[^>]*)'.str_replace('/','\/',$value).'(?![^<]*>)/i';
			    $replace[$key]=get_star_url($value);
			}else{
				continue;
			}
		}
		if(!empty($find) && !empty($replace)){
		   $content = preg_replace($find,$replace,$content,1);
		}
	}
	if($data['vod_id'] && empty($role)){
		$role=db('role')->where('role_vid',$data['vod_id'])->field('role_id,role_name,role_star,role_cid')->select();
	    if($role){
		    foreach($role as $key=>$value){
				if(empty($value['role_name'])){
					continue;
					
				}
				if(strpos($content,$value['role_name']) !== false){
		            $roleurl=zanpian_read_url('home/role/read',$value,$data);
		            $role_find[$key]='<role><a target="_blank" href="'.$roleurl.'" title="'.$value['role_star'].'饰'.$value['role_name'].'">'.$value['role_name'].'</a></role><star>('.get_star_url($value['role_star']).'饰)</star>';
		            // $star='<star>('.get_star_url($value['role_star'],'no').'饰)</star>';
		            $role_replace[$key]='/(?!<[^>]*)'.str_replace(array('/','（','）','(',')'),array('\/','','','',''),$value['role_name']).'(?![^<]*>)/i';
				}else{
				    continue;
			    }
		    }
			if(!empty($role_find) && !empty($role_replace)){
                $content = preg_replace($role_replace,$role_find,$content,1);
            }				
	    }
	}
	return $content;
}
//更具明星名字循环生成URL
function get_star_url($actors,$k="",$keyword="",$type='<a href="#url#" target="_blank">#name#</a> '){
	if(empty($actors)){
		return false;
	}
	if(!is_array($actors)) {
        $actors = array_filter(explode(',', $actors));
    }
	foreach($actors as $key=>$v){
		if($v=="未知"){
			unset($actors[$key]);
		}
	}
	if(!empty($k)){
		$actors=array_slice($actors,0,intval($k));
	}
	if(count($actors)>1) {
		$where['star_name'] = array('in',$actors);
	}
	if(count($actors)==1){
		$where['star_name'] = array('eq',$actors[0]);
	}
	$html = '';
	if($where && strpos($type,'#url#')>0){
	    $list=db('star')->where($where)->column('star_id,star_cid,star_name,star_letters,star_jumpurl,star_hits','star_name');
	}
	foreach($actors as $key=>$v){
		if(!empty($k) && $key==$k){break;}
		if($list[$v]){
		    $url = zanpian_read_url('home/star/read',$list[$v]);
		}else{
			$url = zanpian_url('home/search/index',array('wd'=>urlencode(trim($v))),true,false);
		}
		if($keyword){
			$v = get_hilight_ex($v,$keyword,'font','red');	
		}		
		$arr = $v;
		$html .= str_replace(array('#url#','#name#'),array($url,$arr),$type);
	}
	return $html;
}
function get_star_array($actors='',$k=''){
	if(empty($actors)){
		return false;
	}
	if(!is_array($actors)) {
        $actors = array_filter(explode(',', $actors));
    }
	foreach($actors as $key=>$v){
		if($v=="未知"){
			unset($actors[$key]);
		}
	}
	if(!empty($k)){
		$actors=array_slice($actors,0,intval($k));
	}
	if(count($actors)>1) {
		$where['star_name'] = array('in',$actors);
	}
	if(count($actors)==1){
		$where['star_name'] = array('eq',$actors[0]);
	}
	if($where){
	    $list=db('star')->where($where)->column('*','star_name');
	    foreach($actors as $key=>$v){
			if($list[$v]){
		      $data[$key] = $list[$v];
			}
	    }
		return $data;
	}else{
		return false;
	}	
	
}
//更具电台名字循环生成URL
function get_tv_url($tvs,$k="",$type='<a href="#url#" target="_blank">#name#</a> '){
	if(empty($tvs)){
		return false;
	}
	if(!is_array($tvs)) {
        $tvs = array_filter(explode(',', $tvs));
    }
	if(count($tvs)>1) {
		$where['tv_name'] = array('in',$tvs);
	}else{
		$where['tv_name'] = array('eq',$tvs[0]);
	}		
	$html = '';
	$list=db('tv')->where($where)->field('tv_id,tv_cid,tv_letters,tv_name')->select();
	foreach($list as $key=>$v){
		if(!empty($k) && $key==$k){break;}
		$url = zanpian_read_url('home/tv/read',$v);		
		$arr = $v['tv_name'];
		$html .= str_replace(array('#url#','#name#'),array($url,$arr),$type);
	}
	return $html;
}
function get_vod_url($name,$type,$tvname=''){
	$list = db('vod')->field('vod_id,vod_cid,vod_letters,vod_name,vod_jumpurl')->where(['vod_name'=>$name,'vod_status'=>1])->limit(1)->order('vod_id desc')->cache(600)->find();
	if(empty($list)){	
	    $list = db('vod')->field('vod_id,vod_cid,vod_letters,vod_name,vod_jumpurl')->where(['vod_aliases'=>$name,'vod_status'=>1])->limit(1)->order('vod_id desc')->cache(600)->find();	
	}	
	//if(empty($list) && !empty($type)){	
	//    $where['vod_name'] = array('like',$name.'%');	
	//    $where['vod_status'] = array('eq',1);
    //    $list = db('vod')->field('vod_id,vod_cid,vod_letters,vod_name,vod_jumpurl')->where($where)->limit(1)->order('vod_id desc')->cache(600)->find();
	//}
	if(!empty($list)){
		if(!empty($tvname)){
			$diantai=implode(',',array_unique(explode(',',implode(',',model('Vodtv')->tv_data($list['vod_id'],1)).','.$tvname)));
			model('Vodtv')->tv_updata($list['vod_id'],1,$diantai);
			db('vod')->where('vod_id',$list['vod_id'])->setField('vod_diantai',$diantai);
		}
		return  $list;
	}
	return "";
}
//通过栏目ID返回小分类其它值按数组方式
function get_list_mcat($cid){
	if(!empty($cid)){
		$list=F('_data/list');
		$mcat = model('mcat')->listData();
	    $list_pid=$list[$cid]['list_pid'];
	    $cid=empty($list_pid) ? $cid : $list_pid;
		$list_mcid=$mcat[$cid]['son'];
		if(!empty($list_mcid)){
		    return	$list_mcid ;
		}
	}
	return false;
}
function mcat_title($str,$cid="",$k=""){
	if(empty($str)){
		return "";
	}
	$mcids = explode(',', $str);
	$html = '';
	foreach($mcids as $v){
		$arr= model('mcat')->listMcid();
		$html .= $arr[$v]['m_name'];
	}
	return $html;
}
function mcat_name($str,$cid="",$k=""){
	if(empty($str)){
		return "未知";
	}
	$mcids = explode(',', $str);
	$html = '';
	foreach($mcids as $key=>$v){
	if(!empty($k) && $key==$k){break;}	
       $arr= model('mcat')->listMcid();
	   if(!empty($arr)){
		   $html .= $arr[$v]['m_name']." ";
	   }
	}
	return $html;
}
// 获取某图片的访问地址
function zanpian_avatar_url($data=[],$size='middle'){
	if($data['user_pic']){
		$type=strtolower(pathinfo($data['user_pic'], PATHINFO_EXTENSION));
		$img=zanpian_img_url($data['user_pic'].'_'.$size.'.'.$type);
	}elseif($data['qq_pic']){
		return $data['qq_pic'];
	}elseif($data['weibo_pic']){
		return $data['weibo_pic'];
	}elseif($data['weiqrcode_pic']){
		return $data['weiqrcode_pic'];
	}else{
		// $img=TPL_PATH.'tpl/zanpianadmin/noavatar_'.$size.'.gif';
		$img = 'https://wxt.sinaimg.cn/large/628d024fgy1g5tfklg1lsg205k05kt8n.gif';
	}
	return $img;
}
function pic_graph_domain($url){  
    $upload=config('upload');
	if(!empty($upload['upload_graph_domain'])){
	$upload_graph_domain=parse_config_attr(parse('textarea',$upload['upload_graph_domain']));
		foreach ($upload_graph_domain as $key => $value){
            if(strpos($url,$value)>0){
			 	return true; 
			}
		}	
	} 
	return false; 
}
function parse_config_attr($string) {
	if(is_array ($string)){
	return $string;	
	}	
	$array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
	if (strpos($string, ':')) {
		$value = array();
		foreach ($array as $val) {
			list($k, $v) = explode(':', $val);
			$value[$k]   = $v;
		}
	} else {
		$value = $array;
	}
	return $value;
}
// 获取某图片的访问地址
function zanpian_img_url($file,$default=''){
	if(empty($file)){
		if($default=='default'){
			return '';
		}
		$site_cssjsurl=$GLOBALS['config']['system']['system_cssurl'];
		$public=!empty($site_cssjsurl) ? $site_cssjsurl : TPL_PATH.'tpl/';
		return !empty($default) ? $default : $public."zanpianadmin/no.jpg";
	}
	
	if(strstr($file, 'sinaimg') && $default) {
		$file = str_replace('large', $default, $file);
	}
	
	if (substr($file,0,4) == 'http' || substr($file,0,2) == '//'){
		return $file;
	}elseif(substr($file, 0, 8) == 'zanpian:'){
		if($GLOBALS['config']['upload']['upload_graph_http']==1){
		     return str_replace('zanpian://','//',$file);
		}
		if($GLOBALS['config']['upload']['upload_graph_http']==2){
		     return str_replace('zanpian://','http://',$file);
		}
		if($GLOBALS['config']['upload']['upload_graph_http']==3){
		     return str_replace('zanpian://','https://',$file);
		}		
	}elseif(substr($file, 0,5) == 'error'){
		return !empty($default) ? $default : $public."zanpianadmin/no.jpg";
	}
	elseif(substr($file, 0,1) == '/'){
		if($GLOBALS['config']['upload']['upload_type'] == 0 && $GLOBALS['config']['upload']['upload_http_prefix']){
			return $GLOBALS['config']['upload']['upload_http_prefix'].$file;
		}else{
			return $file;
		}
	}else{	
		if($GLOBALS['config']['upload']['upload_type'] == 0 && $GLOBALS['config']['upload']['upload_http_prefix']){
			return $GLOBALS['config']['upload']['upload_http_prefix'].$file;
		}else{
			if($GLOBALS['config']['upload']['upload_http_prefix']){
			    return $GLOBALS['config']['upload']['upload_http_prefix'].$file;
			}else{
				return URL_PATH.$GLOBALS['config']['upload']['upload_path'].'/'.$file;
			}
		}
	}
}
//过滤内容中的图片
function zanpian_content_image_filter($content){
	 $content= preg_replace('/<img(.*?)>/si',"",$content);
	 return $content;
}
// 提取内容中图片为缩略图
function zanpian_content_pic($content,$size=''){
	if(empty($size)){
	    $config=$GLOBALS['config']['upload'];
		$size=$config['upload_pic'];
	}
	$imgarr=zanpian_image_array($content);
	
	//只有一张图片提取第一张
    if(count($imgarr)== 1){	
	    return $imgarr[0];
	}
	if($size==0){
	   return $imgarr[0];	
	}
	foreach($imgarr as $key=>$val){
		$picurl=zanpian_img_url($val);
		//图片为外链图片
	    if(substr($picurl, 0, 2) == '//') {	
	       $picurl='http:'.$picurl;
	    }		
	    elseif(substr($picurl, 0, 1) == '/') {	
	       $picurl='.'.$picurl;
	    }		
	    $pic=@getimagesize($picurl);
		//宽度大于高度
        if($size==1 && $pic[0] > $pic[1]){
	      return $val;
	    }
		//高度大于宽度
		elseif($size==2 && $pic[0] < $pic[1]){
	      return $val;
	    }	 
	}
	return $imgarr[0];
}
//提取内容中图片为数组
function zanpian_image_array($content){
	if($content == null) return false;
    preg_match_all('/<img(.*?)src="(.*?)(?=")/si',$content,$imgarr);///(?<=img.src=").*?(?=")/si
	preg_match_all('/(?<=src=").*?(?=")/si',implode('" ',$imgarr[0]).'" ',$imgarr);
    if(is_array($imgarr[0])){
		return $imgarr[0];
    }
	return false;
}
//正则提取正文里图片为数组
function zanpian_content_image_array($content){
	preg_match_all('/<img(.*?)(?=>)/si',$content,$imgarr);
	foreach($imgarr[0] as $key=>$value){
	  preg_match('/(?<=alt=").*?(?=")/si',$value,$title);
	  preg_match('/(?<=src=").*?(?=")/si',$value,$imgurl);
	  $array[$key]['img']=$imgurl[0];
	  $array[$key]['alt']=$title[0];
	}
	return $array;
}
//过滤内容中图片
function zanpian_content_filter_image($content){
	 $content= preg_replace('/<img(.*?)>/si', "", $content);
	 return $content;
}
//保存内容图片
function zanpian_content_down_images($value,$sid){
	$config=$GLOBALS['config']['upload'];
	 if(!empty($value)){
	    if(!empty($config['upload_http']) || !empty($config['upload_http_news']) && $sid=='news'){
	      $img = model('Img');
	        if (!!$path = zanpian_image_array($value)) { //正文内的图片远程路径数组
               $savePath = $img->down_load($path,$sid); //保存图片并获取本地保存绝对路径
			  // print_r($savePath);
               $contents1 = str_ireplace($path,$savePath,$value); //远程图片路径替换为本地绝对路径
			   return $contents1;	
             }else{
		       return $value;  
	        } 
	    }else{
		    return $value;  
	    }
	}else{
	        return $value;
	}	
}
function zanpian_news_img_array($content,$type=""){
	if($content == null) return false;
    $picarray=zanpian_image_array($content);
	$pathArr = array();	
	foreach($picarray as $key => $value) {	
		$pathArr[]= zanpian_img_url($value);
	 } 
	if (is_array($pathArr)) { 
	    return str_ireplace($picarray,$pathArr,$content);
	}
	return $content;
}	

// 根据静态规则生成保存路径
function zanpian_url_html($module,$params){
	$url_html=$GLOBALS['config']['html'];
	$old = array('{cid}','{dir}','{vcid}', '{vdir}','{vid}', '{pinyin}','{id}', '{md5}', '{page}', '{sid}', '{pid}');
	if(strpos($module,'show') !== false){
	$new = array($params['id'], $params['dir'], $params['vcid'],$params['vdir'],$params['vid'],$params['pinyin'], $params['id'], md5($params['id']), $params['p'], $params['sid'], $params['pid']);
	}else{
	$new = array($params['cid'], $params['dir'], $params['vcid'],$params['vdir'],$params['vid'],$params['pinyin'], $params['id'], md5($params['id']), $params['p'], $params['sid'], $params['pid']);	
	}	
	if('home/vod/read' == $module){
		$html_path = $url_html['url_vod_data'];
	}else if('home/vod/play' == $module){
		$html_path = $url_html['url_vod_play'];
	}else if('home/vod/filmtime' == $module){
		$html_path = $url_html['url_vod_filmtime'];
	}else if('home/vod/music' == $module){
		$html_path = $url_html['url_vod_music'];
	}else if('home/vod/lines' == $module){
		$html_path = $url_html['url_vod_linesss'];
	}else if('home/vod/show' == $module){
		$html_path = $url_html['url_vod_list'];
	}else if('home/news/read' == $module){
		$html_path = $url_html['url_news_data'];
	}else if('home/news/show' == $module){
		$html_path = $url_html['url_news_list'];
	}else if('home/star/read' == $module){
		$html_path = $url_html['url_star_data'];
	}else if('home/star/info' == $module){
		$html_path = $url_html['url_star_info_data'];
	}else if('home/star/show' == $module){
		$html_path = $url_html['url_star_list'];
	}else if('home/story/read' == $module){
		$html_path = $url_html['url_story_data'];
	}else if('home/part/read' == $module){
		$html_path = $url_html['url_part_data'];
	}else if('home/story/show' == $module){
		$html_path = $url_html['url_story_list'];
	}else if('home/actor/read' == $module){
		$html_path = $url_html['url_actor_data'];
	}else if('home/actor/show' == $module){
		$html_path = $url_html['url_actor_list'];
	}else if('home/role/read' == $module){
		$html_path = $url_html['url_role_data'];
	}else if('home/role/show' == $module){
		$html_path = $url_html['url_role_list'];
	}else if('home/special/read' == $module){
		$html_path = $url_html['url_special_data'];
	}else if('home/special/show' == $module){
		$html_path = $url_html['url_special_list'];
	}else if('home/tv/show' == $module){
		$html_path = $url_html['url_tv_list'];
	}else if('home/tv/read' == $module){
		$html_path = $url_html['url_tv_data'];
	}else if('home/my/show' == $module){
		$html_path = $url_html['url_my_list'];
	}else if('home/map/show' == $module){
		$html_path = $url_html['url_map_list'];
	}else{
		return false;
	}
	if(!$html_path){
		return false;
	}	
	$html_path = str_replace($old,$new,$html_path);
	//第一页去除页码规则
	if($module!='home/vod/play' && $module!='home/part/read'){
	    if($params['p'] == 1 || $module!='home/vod/play'){
		    $html_path .= '[zanpianpage]';
		    $old = array( '/1[zanpianpage]', '-1[zanpianpage]', '_1[zanpianpage]', '-[zanpianpage]', '_[zanpianpage]');
		    $new = array('/index[zanpianpage]', '[zanpianpage]', '[zanpianpage]', '[zanpianpage]', '[zanpianpage]');
		    $html_path = str_replace('[zanpianpage]', '', str_replace($old, $new, $html_path));
	   }
	}
	//首页index处理
	$suffix = strrchr($html_path,'/');
	if($suffix == '/'){
		$html_path .= 'index';
	}	
	return URL_PATH.$html_path;	
}
//静态模式 格式化页码为1的首个链接
function zanpian_url_replace_html($model,$url,$redirect=true,$suffix=false){
	$url_html=$GLOBALS['config']['html'];
	if($model!='home/vod/play' && $model!='home/part/read'){
	$old = array('/index.'.$url_html['url_html_suffix'], '-1.'.$url_html['url_html_suffix'], '_1.'.$url_html['url_html_suffix']);
	$new = array('/', '.'.$url_html['url_html_suffix'], '.'.$url_html['url_html_suffix']);
	$url = str_replace($old, $new, $url);
	}
	if($suffix=='true'){
		$suffix=request()->domain();	
	}
	return $suffix.$url;
}

// 动态模式 自定义路由反向生成对应的链接URL
function url_user_route($model,$params,$redirect=true,$suffix=false){
	$url_rewrite=$GLOBALS['config']['rewrite'];
	if($suffix=='true'){
		$suffix=request()->domain().URL_PATH;	
	}elseif(!empty($suffix) && filter_var(trim($suffix),FILTER_VALIDATE_URL)){
		$suffix=$suffix.URL_PATH;
	}else{
	    $suffix=URL_PATH;
	}
	$url_rules = $url_rewrite['route_rules'];
    $array_key = explode('/',$model);
	if(is_array($params)){
	    foreach($params as $key=>$value){
		    array_push($array_key, $key);
	    }
	}
	//根据U参数生成KEY值
	$key = implode('/',$array_key);
	//将对应的URL网址按对应规则替换
	if($key){
		//判读有无参数没有参数直接替换
		if($url_rules[$key]['find']==1){
			 $url=$url_rules[$key]['replace'];
		}else{
		     $url = str_replace('','',str_replace($url_rules[$key]['find'],$params,$url_rules[$key]['replace']));
		}
		if(!empty($url)){
		  //规则结尾有/不增加后缀
		  if(substr($url_rules[$key]['replace'],-1)=="/"){
	        return $suffix.$url;	
		  }else{
			if($model=='home/map/show'){
			    return $suffix.$url.'.xml';
            }else{
				return $suffix.$url.'.'.$url_rewrite['url_rewrite_suffix'];
			}	
		  }
	    }
	}
}
// 重写动态路径
function zp_url($model,$params='',$redirect=true,$suffix=false){
	return str_replace('?s=/','?s=',url($model,$params,$redirect,$suffix)); 
}

// 重写动态路径
function zanpian_url($model,$params='',$redirect=true,$suffix=false){
	if(!empty($redirect)){
		$redirect=true;
	}
	if(!empty($suffix)){
		$suffix=true;
	}	
	$model=strtolower($model);
	$reurl='';
	// 自定义伪静态规则替换
	if(!empty($GLOBALS['config']['rewrite']['url_rewrite'])){
		if(!empty($GLOBALS['config']['rewrite']['url_rewrite_route'])){
		    $reurl = url_user_route($model,$params,$redirect,$suffix);
		}		
	    //伪静态配置正确
	   if(!empty($reurl)){
	         return $reurl;
	   }else{
		  if(is_array($params)){
			unset($params['pinyin']);
            if(strpos($model,'user/center')===false){
			    unset($params['cid']);
            }			 
			 
			 unset($params['dir']);
			 if(strpos($model,'home/star')===false){
			    unset($params['vcid']);
			    
             }	
             unset($params['vdir']);			 
	         unset($params['mename']);
	         unset($params['earea']);			 
		  }
		$reurl=url($model,$params,$redirect,$suffix);	  
	   }			
	}else{
		$reurl=url($model,$params,$redirect,$suffix); 
	}
	if(ENTRANCE!='index' || ENTRANCE=='index'){
		if($GLOBALS['config']['system']['system_pathinfo']=='/'){
		    $url = 'index.php';
		    $reurl=str_replace(PATH_FILE,$url,$reurl);		
		}else{
			$reurl=str_replace(PATH_FILE.'/','?s=',$reurl);
		}
		if(!empty($GLOBALS['config']['rewrite']['url_rewrite'])){
		    if(empty($GLOBALS['config']['html']['url_html']) && false !== strpos($model,'home/barrage')  &&  false !== strpos($model,'home/digg') &&  false !== strpos($model,'home/hits')){
		        return str_replace(array('index.php','?s='),'',$reurl);
	        }else{
				return str_replace('?s=','index.php?s=',$reurl);
			}
		}else{
		    if(!empty($GLOBALS['config']['html']['url_html'])){
		        return str_replace('?s=','index.php?s=',$reurl);
	        }			
		}	
	}
	return $reurl;  

}
// 重写会员动态
function zanpian_user_url($model,$arrurl=[],$redirect=true,$suffix=false){
	if($model=='user/home/index'){
		$array['id']=$arrurl['user_id'];
	}else{
		$array=$arrurl;
	}
	return zanpian_url($model,$array,$redirect,$suffix);
}
// 重写会员动态
function zanpian_api_url($model,$arrurl=[],$redirect=true,$suffix=false){
	$reurl=url($model,$arrurl,$redirect,$suffix);
	if(ENTRANCE!='api' || ENTRANCE=='api'){
	    $reurl=str_replace(PATH_FILE,'api.php',$reurl);
	}
	return $reurl;
}
function zanpian_list_url($model='',$arrurl='',$redirect=true,$suffix=false){
	return zanpian_data_url($model,$arrurl,$redirect,$suffix);
}
function zanpian_show_url($arrurl='',$redirect=true,$suffix=false){
	    if(is_array($arrurl)) {
	        if($arrurl['list_id']){
		        $array['id']=$arrurl['list_id'];
	        }
			if($arrurl['list_dir']){
			    $array['dir']=$arrurl['list_dir'];
	        }else{
			    $array['dir']=getlistname($arrurl['list_id'],'list_dir');
		    }
		    if($arrurl['p']){
		        $array['p']=$arrurl['p'];
	        }else{
				$array['p']=1;
			}
			$name=getlistname($arrurl['list_id'],'name');
			$model='home/'.$name.'/show';
		}else{
            $info=getlistname($arrurl,'info');
			if(is_array($info)){
				$array['id']=$info['list_id'];
				$array['dir']=$info['list_dir'];
				$model='home/'.$info['name'].'/show';
			}else{
				$array = [];
			}
		}
	return zanpian_data_url($model,$array,$redirect,$suffix);
}
function zanpian_type_url($model='home/vod/type',$arrurl='',$redirect=true,$suffix=false){	
	return zanpian_data_url($model,$arrurl,$redirect,$suffix);
}

function zanpian_read_url($model='home/vod/read',$arrurl=[],$params=[],$redirect=true,$suffix=false){
	if(!empty($params)){
	    $arrurl=array_merge($arrurl,$params);
	}
	if($model=='home/vod/read' || $model=='home/vod/music' || $model=='home/vod/news' || $model=='home/vod/filmtime' || $model=='home/vod/lines'){
	    if(!empty($arrurl['vod_id'])){
		    $array['id']=$arrurl['vod_id'];
	    }
	    if(!empty($arrurl['vod_letters'])){
		    $array['pinyin']=$arrurl['vod_letters'];
	    }	
	    if(!empty($arrurl['vod_cid'])){
		    $array['cid']=$arrurl['vod_cid'];
		    $array['dir']=getlistname($arrurl['vod_cid'],'list_dir');
	    }
	    if(!empty($arrurl['vod_jumpurl'])){
		    $array['jumpurl']=$arrurl['vod_jumpurl'];
	    }
    }elseif($model=='home/actor/read'){
	    if(!empty($arrurl['actor_id'])){
		   $array['id']=$arrurl['actor_id'];
	    }
	    if(!empty($arrurl['actor_vid'])){
		   $array['vid']=$arrurl['actor_vid'];
	    }
	    if(empty($array['actor_vid']) && !empty($arrurl['vod_id'])){
		   $array['vid']=$arrurl['vod_id'];
	    }		
	    if(!empty($arrurl['vod_letters'])){
		   $array['pinyin']=$arrurl['vod_letters'];
	    }	
	    if(!empty($arrurl['actor_cid'])){
		   $array['cid']=$arrurl['actor_cid'];
		   $array['dir']=getlistname($arrurl['actor_cid'],'list_dir');
	    }
	    if(!empty($arrurl['vod_cid'])){
		   $array['vcid']=$arrurl['vod_cid'];
		   $array['vdir']=getlistname($arrurl['vod_cid'],'list_dir');
	    }
	}elseif($model=='home/role/read'){
	    if(!empty($arrurl['role_id'])){
		   $array['id']=$arrurl['role_id'];
	    }
	    if(!empty($arrurl['role_vid'])){
		   $array['vid']=$arrurl['role_vid'];
	    }
	    if(empty($array['role_vid']) && !empty($arrurl['vod_id'])){
		   $array['vid']=$arrurl['vod_id'];
	    }		
	    if(!empty($arrurl['vod_letters'])){
		   $array['pinyin']=$arrurl['vod_letters'];
	    }	
	    if(!empty($arrurl['role_cid'])){
		   $array['cid']=$arrurl['role_cid'];
		   $array['dir']=getlistname($arrurl['role_cid'],'list_dir');
	    }
	    if(!empty($arrurl['vod_cid'])){
		   $array['vcid']=$arrurl['vod_cid'];
		   $array['vdir']=getlistname($arrurl['vod_cid'],'list_dir');
	    }
	}elseif($model=='home/story/read'){
	    if(!empty($arrurl['story_id'])){
		   $array['id']=$arrurl['story_id'];
	    }
	    if(!empty($arrurl['story_vid'])){
		   $array['vid']=$arrurl['story_vid'];
	    }
	    if(empty($array['story_vid']) && !empty($arrurl['vod_id'])){
		   $array['vid']=$arrurl['vod_id'];
	    }			
	    if(!empty($arrurl['vod_letters'])){
		   $array['pinyin']=$arrurl['vod_letters'];
	    }	
	    if(!empty($arrurl['story_cid'])){
		   $array['cid']=$arrurl['story_cid'];
		   $array['dir']=getlistname($arrurl['story_cid'],'list_dir');
	    }
	    if(!empty($arrurl['vod_cid'])){
		   $array['vcid']=$arrurl['vod_cid'];
		   $array['vdir']=getlistname($arrurl['vod_cid'],'list_dir');
	    }			
	}elseif($model=='home/part/read'){
	    if(!empty($arrurl['part_id'])){
		   $array['id']=$arrurl['part_id'];
	    }
	    if(!empty($arrurl['story_id'])){
		   $array['sid']=$arrurl['story_id'];
	    }
	    if(!empty($arrurl['part_vid'])){
		   $array['vid']=$arrurl['part_vid'];
	    }		
	    if(!empty($arrurl['vod_letters'])){
		   $array['pinyin']=$arrurl['vod_letters'];
	    }		
	    if(!empty($arrurl['story_cid'])){
		   $array['cid']=$arrurl['story_cid'];
		   $array['dir']=getlistname($arrurl['story_cid'],'list_dir');
	    }		
	    if(!empty($arrurl['vod_cid'])){
		   $array['vcid']=$arrurl['vod_cid'];
		   $array['vdir']=getlistname($arrurl['vod_cid'],'list_dir');
	    }
	    if(!empty($arrurl['part_oid'])){
		   $array['p']=$arrurl['part_oid'];
	    }
	}elseif($model=='home/special/read'){
	    if(!empty($arrurl['special_id'])){
		   $array['id']=$arrurl['special_id'];
	    }
	    if(!empty($arrurl['special_letters'])){
		   $array['pinyin']=$arrurl['special_letters'];
	    }	
	    if(!empty($arrurl['special_cid'])){
		   $array['cid']=$arrurl['special_cid'];
		   $array['dir']=getlistname($arrurl['special_cid'],'list_dir');
	    }
	    if(!empty($arrurl['special_jumpurl'])){
		   $array['jumpurl']=$arrurl['special_jumpurl'];
	    }
	}elseif($model=='home/news/read'){
	    if(!empty($arrurl['news_id'])){
		   $array['id']=$arrurl['news_id'];
	    }	
	    if(!empty($arrurl['news_cid'])){
		   $array['cid']=$arrurl['news_cid'];
		   $array['dir']=getlistname($arrurl['news_cid'],'list_dir');
	    }
	    if(!empty($arrurl['p'])){
		   $array['p']=$arrurl['p'];
	    }
	    if(!empty($arrurl['news_jumpurl'])){
		   $array['jumpurl']=$arrurl['news_jumpurl'];
	    }
	}elseif($model=='home/star/read' || $model=='home/star/info' || $model=='home/star/hz' || $model=='home/star/news' || $model=='home/star/role'  || $model=='home/star/work'){
		if(empty($arrurl['star_id']) && !empty($arrurl['role_star'])){
			$model='home/search/index';
			$array['wd']=urlencode(trim($arrurl['role_star']));
		}else{		
    	    if(!empty($arrurl['star_id'])){
		        $array['id']=$arrurl['star_id'];
	        }
	        if(!empty($arrurl['star_letters'])){
		        $array['pinyin']=$arrurl['star_letters'];
	        }	
	        if(!empty($arrurl['star_cid'])){
		        $array['cid']=$arrurl['star_cid'];
		        $array['dir']=getlistname($arrurl['star_cid'],'list_dir');
	        }
	        if(!empty($arrurl['vcid'])){
		        $array['vcid']=$arrurl['vcid'];
		        $array['vdir']=getlistname($arrurl['vcid'],'list_dir');
	        }			
	        if(!empty($arrurl['star_jumpurl'])){
		        $array['jumpurl']=$arrurl['star_jumpurl'];
	        }
		}		
	}elseif($model=='home/tv/read'){
	    if(!empty($arrurl['tv_id'])){
		   $array['id']=$arrurl['tv_id'];
	    }
	    if(!empty($arrurl['tv_letters'])){
		        $array['pinyin']=$arrurl['tv_letters'];
	    }		
	    if(!empty($arrurl['tv_cid'])){
		   $array['cid']=$arrurl['tv_cid'];
		   $array['dir']=getlistname($arrurl['tv_cid'],'list_dir');
	    }
	    if(!empty($arrurl['p'])){
		   $array['p']=$arrurl['p'];
	    }
	    if(!empty($arrurl['tv_jumpurl'])){
		   $array['jumpurl']=$arrurl['news_jumpurl'];
	    }
	}	
	return zanpian_data_url($model,$array,$redirect,$suffix);
}
function zanpian_data_url($model='home/vod/read',$arrurl=[],$redirect=true,$suffix=false){
	//有跳转地址
	if (!empty($arrurl['jumpurl'])) {
		 return $arrurl['jumpurl'];
	}
	if($GLOBALS['config']['html']['url_html']){
		$url=zanpian_url_html($model,$arrurl);
		if($url){
			if($model=='home/map/show'){
				$url= $url.'.xml';
			}else{
		       $url= $url.'.'.$GLOBALS['config']['html']['url_html_suffix'];
			}
		    return zanpian_url_replace_html($model,$url,$redirect,$suffix);
		}
	}	
	if(empty($GLOBALS['config']['rewrite']['url_rewrite']) || !empty($GLOBALS['config']['rewrite']['url_rewrite']) && empty($GLOBALS['config']['rewrite']['url_rewrite_user'])){
	unset($arrurl['pinyin']);
	unset($arrurl['cid']);
	unset($arrurl['vid']);
	if(strpos($model,'home/ajax')===false && strpos($model,'home/vod')===false){
	unset($arrurl['sid']);
	}	
	unset($arrurl['dir']);
	if(strpos($model,'home/star')===false){
	unset($arrurl['vcid']);
	}
	unset($arrurl['vdir']);	
	unset($arrurl['mename']);
	unset($arrurl['earea']);
    }
	unset($arrurl['jumpurl']);
	if(!empty($arrurl['p'])){
        if($arrurl['p'] > 1){
	        $arrurl['p'] = $arrurl['p'];
	    }
		if($arrurl['p']==1 && $model!='home/part/read' && $model!='home/tv/read'){
	        unset($arrurl['p']);			
	    }
	}
	return zanpian_url($model,$arrurl,$redirect,$suffix);
}
function zanpian_play_url($arrurl=[],$params=[],$redirect=true,$suffix=false){
	if(!empty($params)){
	    $arrurl=array_merge($arrurl,$params);
	}	
	if($GLOBALS['config']['video']['video_play']==2 || $arrurl['vod_copyright']==3){
		return $arrurl['path'];
	}
	if(!empty($arrurl['vod_id'])){
		$array['id']=$arrurl['vod_id'];
	}
	if(!empty($arrurl['vod_letters'])){
		$array['pinyin']=$arrurl['vod_letters'];
	}		
	if(!empty($arrurl['vod_cid'])){
		$array['cid']=$arrurl['vod_cid'];
		$array['dir']=getlistname($arrurl['vod_cid'],'list_dir');
	}
	if(isset($arrurl['sid'])){
		$array['sid']=$arrurl['sid'];
	}
	if(!empty($arrurl['pid'])){
		$array['pid']=$arrurl['pid'];
	}	
	if($GLOBALS['config']['html']['url_html']){
		$url=zanpian_url_html('home/vod/play',$array);
		if($url){
		    $url= $url.'.'.$GLOBALS['config']['html']['url_html_suffix'];
		    return zanpian_url_replace_html('home/vod/play',$url);
		}
	}
	//动态模式销毁变量
	if(empty($GLOBALS['config']['rewrite']['url_rewrite']) || !empty($GLOBALS['config']['rewrite']['url_rewrite']) && empty($GLOBALS['config']['rewrite']['url_rewrite_user'])){
	   unset($array['pinyin']);
	   unset($array['cid']);
	   unset($array['dir']);
    }
	return zanpian_url('home/vod/play',$array,$redirect,$suffix);
}

function get_Key($id){
	if($id){
	    $name=md5($id);
		return substr($name, 0, 2) . DS . substr($name,2, 2). DS . substr($name,4, 2). DS . $name;
	}
}
function get_part_id($id){
	if($id){
	    $vod_id=db('part')->where('part_id',$id)->value('part_vid');
		if(!empty($vod_id)){
			return get_Key($vod_id);
		}
	}
}

function get_role_id($id){
	if($id){
	    $vod_id=db('role')->where('role_id',$id)->value('role_vid');
		if(!empty($vod_id)){
			return get_Key($vod_id);
		}
	}
}
function time_format($time = NULL,$format='Y-m-d H:i',$type=''){
    $time = $time === NULL ? time() : intval($time);
    if(empty($type)){
    	return date($format, $time);
    }else{
    	$current_time=time();
	    $span=$current_time-$time;
	    if($span<60){
	        return "刚刚";
	    }else if($span<3600){
	        return intval($span/60)."分钟前";
	    }else if($span<24*3600){
	        return intval($span/3600)."小时前";
	    }else if($span<(7*24*3600)){
	        return intval($span/(24*3600))."天前";
	    }else if($span<(4*7*24*3600)){
	        return intval($span/(24*3600))."天前";
	    }else{
	        return date($format,$time);
	    }
    } 
}
function time_day($time,$new='<span class="new"></span>'){
    if(!is_numeric($time)){
        $time = strtotime($time);
    }	
	if((time()-$time)>86400){
	    return ;
	}else{
	     return ''.$new.'';
	}
}
function time_today($time,$f='',$c='red'){
    if(empty($time)) { return ''; }
    if(is_numeric($time)){
        $time = date('Y-m-d H:i:s',$time);
    }
    $now = date('Y-m-d',time());
    if($f=='color' && strpos(','.$time,$now)>0){
        return '<font color="' .$c. '">' .$time. '</font>';
    }
    return  $time;
}
function like_array($value){
    $array = explode(',',$value);
    foreach($array as $k=>$v){
        $array[$k] = '%'.$v.'%';
    }
    return $array;
}
function tag_cache($tag){
	$param = zanpiancms_param_url();
	$tag['page']=$param['p'];
	// 缓存参数
	if(!empty($tag['cachename']) ==  'default' || empty($tag['cachename'])){
		$params['cache_name'] = md5($GLOBALS['config']['cache']['prefix'].implode('_',$tag));
	}else{
		$params['cache_name']= !empty($tag['cachename']) ? md5($GLOBALS['config']['cache']['prefix'].'_'.$tag['cachename']) : '';
	}
	// 缓存时间
	$params['cache_time']= !empty($tag['cachetime']) ? intval($tag['cachetime']) : intval($GLOBALS['config']['cache']['cache_foreach']);
	return $params;
}
//关联统计
function topic_count($array=[]){
	if($array){
		$where=array();
		if($array['topic_tid']){
			$where['topic_tid']=$array['topic_tid'];
		}
		if($array['topic_sid']){
			$where['topic_sid']=$array['topic_sid'];
		}
		if($array['topic_did']){
			$where['topic_did']=$array['topic_did'];
		}
		if($array['topic_tsid']){
			$where['topic_tsid']=$array['topic_tsid'];
		}
 		if($array['topic_count']){
			$count=$array['topic_count'];
		}
        if($array['topic_cache']){
			$cachename = md5($GLOBALS['config']['cache']['prefix'].implode('_',$array));
			$cachetime=intval($array['topic_cache']);
			$data_cache_content = cache($cachename);
			if($data_cache_content){
				return $data_cache_content;
			}			
		}
		$data=db('topic')->where($where)->count($count);
		if(!empty($cachename) && !empty($cachetime)){
			cache($cachename,$data,intval($cachetime)); 
	    }		
		return $data;
	}else{
		return 0;	
	}
}	
function check_position($id,$type=''){
	if(empty($type)){
		$array=parse('textarea',config('setting.document_position'));
	}else{
	    $array=parse('textarea',config('setting.week_list'));
	}
	$array=array_keys($array);
    $res[] = $array;
    for($i=2; $i<count($array); $i++) $res = array_merge($res, Combination($array, $i));
    foreach($res as $key=>$v){ 
	//print_r($v);
	    if($id==array_sum($v)){
			return array('eq',''.$id.'');  	
		}
        elseif(in_array($id,$v)){
			$ids[]=  array_sum($v);
		}
		continue;
    }
	if(!empty($ids)){
	    array_unshift($ids,$id);
	    $mids=implode(',', $ids);
        return array('IN',''.$mids.'');  
	}
	return false;
}
	/**
	 * 根据配置类型解析配置
	 * @param  integer $type  配置类型
	 * @param  string  $value 配置值
	 */
	function parse($type, $value){
		if($value){
		    switch ($type) {
			    case 'textarea': //解析数组
			    $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
			    if(strpos($value,':')){
				    $value  = array();
				        foreach ($array as $val) {
					    $list = explode(':', $val);
					    if(isset($list[2])){
						    $value[$list[0]]   = $list[1].','.$list[2];
					    }else{
						$value[$list[0]]   = $list[1];
					   }
				    }
			    }else{
				$value =    $array;
			    }
			     break;
		    }
		}
		return $value;
	}
	function arr($type,$array){
		switch ($type) {
			case 'textarea': //解析数组
			if(is_array($array)){
				foreach ($array as $key=> $val) {
					$list = explode(',', $val);
					if(isset($list[1])){
						$data[$key]   = $key.':'.$list[0].':'.$list[1];
					}else{
						$data[$key]  = $key.':'.$list[0];
					}					
				}
				$array=implode("\r\n",$data);
			}
			break;
		}
		return $array;
	}
function Combination( $arr,$num=0) {
    $arr = array_values($arr);
    $len = count($arr);
    if($num <= 0 || $num > $len) $num = $len;
    $res = array();
    for($i=1,$n=pow(2, $len); $i<$n; ++$i) {
        $tmp = str_pad(base_convert($i, 10, 2), $len, '0', STR_PAD_LEFT);
        $t = array();
        for($j=0; $j<$len; ++$j) {
            if($tmp{$j} == '1') {
                $t[] = $arr[$j];
            }
        }
        if(count($t) == $num) $res[] = $t;
    }
    return $res;
}	
// 返回下一篇或上一篇的内容的信息
function detail_array($module='vod', $type='next',$id,$cid='', $field='vod_id,vod_cid,vod_status,vod_name,vod_ename,vod_jumpurl'){
	//优先读取缓存数据
	$cache_key = 'cache_'.$module.'_'.$type.'_'.$cid.'_'.$id;
	if(config('data_cache_'.$module)){
		$array = cache($cache_key);
		if($array){
			return $array;
		}
	}
	$where = array();
	if(!empty($cid)){
	    $where[$module.'_cid'] = $cid;
	}
	$where[$module.'_status'] = 1;
	if($type == 'next'){
		$where[$module.'_id'] = array('gt', $id);
		$order = $module.'_id asc';
	}else{
		$where[$module.'_id'] = array('lt', $id);
		$order = $module.'_id desc';
	}

	if($module != 'vod'){
		//$field = str_replace('vod_', $module.'_', $field);
	}
	if($module == 'story' || $module == 'actor' || $module == 'role'){
	       $array = db((ucfirst($module)))->join('vod vod','vod.vod_id ='.$module.'_vid','LEFT')->field($field)->where($where)->order($order)->limit(1)->find();
	}else{
		$array = db((ucfirst($module)))->field($field)->where($where)->order($order)->limit(1)->find();
	}
	// 是否写入缓存
	if(config('data_cache_'.$module)){
		cache($cache_key, $array, intval(config('data_cache_'.$module)));
	}
	return $array;
}
function get_emots($content=false) {
	if(!$content){ return false;}
	$emot=F('_data/emots');
	preg_match_all("/\[.*?\]/", $content,$emots);
	if($emots[0]){
		foreach ($emots[0] as $v) {
		   $var=str_replace(array("[","]"),'',$v);
           $content = str_replace("[" . $var . "]","<img alt='" . $var . "' src='" .TPL_PATH."tpl/zanpianadmin/emot/" . $emot[$var] . ".gif'>", $content);
		}
	}
	return $content;
}
function get_info_find($sid=1,$var,$seach='vod_id',$find="*"){
    $db=$GLOBALS['config']['model'][$sid]['name'];
    $arr= db($db)->field($find)->where($seach,$var)->find();
	if(!empty($arr)){
		return $arr;
	}else{
	    return false ;
	}
}
function get_user_info($var,$seach='user_id',$type=''){
	if($type){
	$info = db('user')->where($seach,$var)->value($type);
	}else{
	$info = db('user')->where($seach,$var)->find();	
	}
	if($info){
		return $info;
	}else{
	    return false ;
	}

}

function num2tring($num) {
	if ($num >= 10000) {
	    $num = round($num / 10000 * 100) / 100 .' 万';
	}//elseif($num >= 1000) {
 	   // $num = round($num / 1000 * 100) / 100 . ' K';
	//}
	else{
  	    $num = $num;
  	}
 	return $num;
}
//生成迅雷地址
function ThunderEncode($url) {
    $thunderPrefix="AA";
    $thunderPosix="ZZ";
    $thunderTitle="thunder://";
    $thunderUrl=$thunderTitle.base64_encode($thunderPrefix.$url.$thunderPosix);
    if (strpos($url,'http://') !== false  || strpos($url,'https://') !== false  || strpos($url,'ftp://') !== false){
        return $thunderUrl;
    }else{
        return $url;
    }

}
function get_time($var){
    $lastTime = session($var);
    if(empty($lastTime)){
        $lastTime= "1228348800";
    }
    $res = time() - intval($lastTime);
    session($var,time());
    return $res;
}
function getpageprev($data){
	if(!empty($data->currentPage())){
	    if(config('route')){
		    $route=config('route');
	    }else{
		    $route=$GLOBALS['route'];
	    }	
	    $params=config('params');
	    $url = urldecode(zanpian_list_url($route,$params));
	    unset($params['p']);
	    $first_url= urldecode(zanpian_list_url($route,$params));	
        if($data->currentPage()> 1){
            $linkPage = str_replace('[PAGE]',$data->currentPage()-1,$url);
	    }
        if($data->currentPage()== 2){
            $linkPage = $first_url;
	    }
        return $linkPage;
	}else{
		return false;
	}
}
function getpagenext($data){
	$linkPage = '';
	if(!empty($data->currentPage())){
	    if(config('route')){
		    $route=config('route');
	    }else{
		    $route=$GLOBALS['route'];
	    }		
	    $params=config('params');	
	    $url = urldecode(zanpian_list_url($route,$params));
        $linkPage .= ($data->currentPage() < $data->lastPage())
        ? str_replace('[PAGE]',($data->currentPage()+1),$url)
        : '';
        return $linkPage;
	}else{
		return false;
	}
}
function page_arry($pageNums='',$page=''){
    if(empty($pageNums) || empty($page)){
	    return false;	
    }
	$pageNums=intval($pageNums);
	$page=intval($page);
    if($page>=$pageNums){
	    return false;	
    }else{
        $ceshi=ceil($pageNums/$page);
	    for($i = 1; $i <= $ceshi; $i++){
		    if($i==1){
		        $fenye[$i]['start']=$i;
			    $fenye[$i]['end']=$page;
		    }elseif($i==$ceshi && ($i*$page+1)>$pageNums){
			    $fenye[$i]['start']=($page*($i-1)+1);
			    if(($page*($i-1)+1)!=$pageNums){
			        $fenye[$i]['end']=$pageNums;
			    }
		    }else{
			    $fenye[$i]['start']=($page*($i-1)+1);
			    $fenye[$i]['end']=($i*$page+1);
		    }
	    }
    }
    return $fenye;		
}
//老版本兼容
//生成参数列表,以数组形式返回
function param_lable($tag = ''){
	$param = array();
	$array = explode(';',str_replace('num:','limit:',$tag));
	foreach ($array as $v){
		list($key,$val) = explode(':',trim($v));
		$param[trim($key)] = trim($val);
	}
	return $param;
}
function zanpian_mysql_vod($tag){
	$tag = param_lable($tag);
	return model('vod')->listData($tag);
}
function zanpian_mysql_star($tag){
	$tag = param_lable($tag);
	return model('star')->listData($tag);
}
function zanpian_mysql_news($tag){
	$tag = param_lable($tag);
	return model('news')->listData($tag);
}
function zanpian_mysql_actor($tag){
	$tag = param_lable($tag);
	return model('actor')->listData($tag);
}
function zanpian_mysql_role($tag){
	$tag = param_lable($tag);
	return model('role')->listData($tag);
}
function zanpian_mysql_story($tag){
	$tag = param_lable($tag);
	return model('story')->listData($tag);
}
function zanpian_mysql_slide($tag){
	$tag = param_lable($tag);
	return model('slide')->listData($tag);
}
function zanpian_mysql_topic($tag){
	$tag = param_lable($tag);
	return model('topic')->listData($tag);
}
function zanpian_mysql_part($tag){
	$tag = param_lable($tag);
	return model('part')->listData($tag);
}
function zanpian_mysql_lines($tag){
	$tag = param_lable($tag);
	return model('lines')->listData($tag);
}
function zanpian_mysql_music($tag){
	$tag = param_lable($tag);
	return model('music')->listData($tag);
}
function zanpian_mysql_cm($tag){
	$tag = param_lable($tag);
	return model('cm')->listData($tag);
}

// by plain

//获取标题第一次出现的数字
function zanpian_name_num($str){
	if(preg_match("/pv|PV|SP|sp|全集|总集|版/", $str)){
		return $str;
	} else {
		preg_match("/\d+/i", $str, $arr);
		if(count($arr)) {
			return $arr[0];
		} else {
			return $str;
		}
	}
}

// 通过 vod_mcid 和 vod_cid 获取 mcid（小分类） 名字
function mcat_json($mcids) {
	if(empty($mcids)){
		return false;
	}
	if(!is_array($mcids)) {
        $mcids = array_filter(explode(',', $mcids));
    }
	$mcid=model('mcat')->listMcid();

	foreach($mcids as $key=>$v){
		$list[$key]['id'] = $v;
		$list[$key]['title'] = $mcid[$v]['m_name'];;
	}
	return $list;
}

// 循环演员名称获取相关明星JSON
function get_star_json($actors) {
	if(empty($actors)){
		return false;
	}
	if(!is_array($actors)) {
        $actors = array_filter(explode(',', $actors));
	}
	foreach($actors as $key=>$v){
		if($v=="未知"){
			unset($actors[$key]);
		}
	}
	if(count($actors)>1) {
		$where['star_name'] = array('in',$actors);
	}
	if(count($actors)==1){
		$where['star_name'] = array('eq',$actors[0]);
	}
	if($where){
	    $list=db('star')->where($where)->column('star_id,star_cid,star_name,star_letters,star_jumpurl,star_hits','star_name');
	}
	$lists = array();
	foreach($actors as $key=>$v){
		if($list[$v]){
			$lists[$key]['id'] = $list[$v]['star_id'];
			$lists[$key]['title'] = $v;
		}else{
			$lists[$key]['title'] = $v;
		}
	}
	return $lists;
}

// 获取影片最后一集array(sid,pid,jiname,jipath)
function play_url_end($vod_url,$vod_play){
    $player = $GLOBALS['config']['play'];
	$arr_server = explode('$$$',trim($vod_url));
	$arr_player= explode('$$$',trim($vod_play));
	foreach ($arr_player as $key=>$value){
		//过滤不存在以及禁用的播放器	
		if(empty($player[$value]) || $player[$value]['play_display']==0 || $value=="down"){
			unset($arr_player[$key]);	//不存在就销毁
			unset($arr_server[$key]);	//不存在就销毁		   
		}else{
			$arr_player[$key] = $arr_server[$key];  
		} 
	}
	if($arr_player){
		foreach($arr_player as $key=>$value){
			$array[$key] = array(count(explode(chr(13),str_replace(array("\r\n", "\n", "\r"),chr(13),$value))),$key);
		}
		$max_key = max($array);
		$array = explode(chr(13),str_replace(array("\r\n", "\n", "\r"),chr(13),$arr_player[$max_key[1]]));
		$arr_url = explode('$',end($array));
		if($arr_url[1]){
			return array($max_key[1],$max_key[0],$arr_url[0],$arr_url[1]);
		}else{
			return array($max_key[1],$max_key[0],'第'.$max_key[0].'集',$arr_url[0]);
		}
	}else{
		return false;
	}
}

//生成播放列表字符串
function playlist_json($vod_url_array) {
	if(empty($vod_url_array)){return false;}
	$key = 0;
	foreach($vod_url_array as $val) {
		$array_urls[$key]['playname'] = $val['play_name'];
		$array_urls[$key]['playtitle'] = $val['play_title'];
		foreach($val['play_urls'] as $keysub => $valsub) {
			$video = array($valsub["name"], $valsub["path"], $valsub["pic"], $valsub["fen"], $valsub["miao"], $valsub["source"], $valsub["pid"]);
			$array_urls[$key]["playurls"][$keysub - 1] = $video;
		}
		$key++;
	}
	return $array_urls;
}

// 格式化时间
function zanpian_from_time($time){
	$way = time() - $time;
	$r = '';
	if($way < 60){
		$r = '刚刚';
	}elseif($way >= 60 && $way < 3600){
		$r = floor($way/60).'分钟前';
	}elseif($way >=3600 && $way < 86400){
		$r = floor($way/3600).'小时前';
	}elseif($way >=86400 && $way < 2592000){
		$r = floor($way/86400).'天前';
	}elseif($way >=2592000 && $way < 31536000){
		$r = floor($way/2592000).'个月前';
	}elseif($way >=2592000 && $way < 63072000){
		$r = floor($way/31536000).'年前';
	}else{
		$r = date('Y-m-d H:i:s', $time);
	}
	return $r;
}

//XSS漏洞过滤
function remove_xss($val) {
	$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
	$search = 'abcdefghijklmnopqrstuvwxyz';
	$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$search .= '1234567890!@#$%^&*()';
	$search .= '~`";:?+/={}[]-_|\'\\';
	for ($i = 0; $i < strlen($search); $i++) {
	   $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
	   $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
	}
	$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	$ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	$ra = array_merge($ra1, $ra2);
	$found = true; // keep replacing as long as the previous round replaced something
	while ($found == true) {
	   $val_before = $val;
	   for ($i = 0; $i < sizeof($ra); $i++) {
		  $pattern = '/';
		  for ($j = 0; $j < strlen($ra[$i]); $j++) {
			 if ($j > 0) {
				$pattern .= '(';
				$pattern .= '(&#[xX]0{0,8}([9ab]);)';
				$pattern .= '|';
				$pattern .= '|(&#0{0,8}([9|10|13]);)';
				$pattern .= ')*';
			 }
			 $pattern .= $ra[$i][$j];
		  }
		  $pattern .= '/i';
		  $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
		  $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
		  if ($val_before == $val) {
			 // no replacements were made, so exit the loop
			 $found = false;
		  }
	   }
	}
	return $val;
}
